<template>
  <el-card class="stat-page">
    <!-- 筛选区 -->
    <div class="header-bar">
      <span class="title">告警统计分析</span>
      <el-radio-group v-model="dateType" size="small" style="margin-right:10px;">
        <el-radio-button label="day">日</el-radio-button>
        <el-radio-button label="month">月</el-radio-button>
        <el-radio-button label="year">年</el-radio-button>
      </el-radio-group>
      <el-select v-model="level" size="small" style="width:100px;margin-right:10px;" clearable>
        <el-option label="全部级别" value="" />
        <el-option label="高" value="高" />
        <el-option label="中" value="中" />
        <el-option label="低" value="低" />
      </el-select>
      <el-select v-model="type" size="small" style="width:130px;margin-right:10px;" clearable>
        <el-option label="全部类型" value="" />
        <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t" />
      </el-select>
      <el-button type="primary" size="small" @click="exportExcel">导出Excel</el-button>
      <el-button size="small" @click="downloadAllImages">下载全部图表</el-button>
    </div>

    <!-- 卡片区 -->
    <el-row :gutter="16" class="stat-cards">
      <el-col :xs="12" :sm="6" v-for="(v, k, i) in cardData" :key="i">
        <el-card shadow="hover">
          <div :class="['card-num', k]">
            {{ cardMap[k] }}<br />{{ v }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区：上 -->
    <el-row :gutter="16" style="margin-top:24px;">
      <el-col :xs="24" :sm="12">
        <el-card>
          <div class="stat-title">告警趋势</div>
          <v-chart ref="trendRef" :option="trendOption" autoresize style="height: 260px; width:100%;" />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12">
        <el-card>
          <div class="stat-title">告警级别分布</div>
          <v-chart ref="levelRef" :option="levelPieOption" autoresize style="height: 260px; width:100%;" />
        </el-card>
      </el-col>
    </el-row>
    <!-- 图表区：下 -->
    <el-row :gutter="16" style="margin-top:24px;">
      <el-col :xs="24" :sm="12">
        <el-card>
          <div class="stat-title">告警类型TOP5</div>
          <v-chart ref="typeTopRef" :option="typeTopOption" autoresize style="height: 260px; width:100%;" />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12">
        <el-card>
          <div class="stat-title">设备告警TOP5</div>
          <v-chart ref="deviceTopRef" :option="deviceTopOption" autoresize style="height: 260px; width:100%;" />
        </el-card>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import VChart from 'vue-echarts'

// 控件状态
const dateType = ref('day')
const level = ref('')
const type = ref('')

// 假数据选项
const typeOptions = [
  '设备故障', '温度过高', '断电', '滤网堵塞', '配件缺失',
  '压力异常', '软件异常', '维护到期'
]

// 基础数据：根据筛选条件动态过滤
const trendDataRaw = {
  day: [
    { date: '6-06', 高: 1, 中: 3, 低: 1, total: 5, types: { '设备故障': 2, '温度过高': 1, '配件缺失': 1, '断电': 1 }, device: { '心电监护仪A': 2, '注射泵B': 1, '呼吸机C': 1, '移动DR': 1 } },
    { date: '6-07', 高: 3, 中: 3, 低: 2, total: 8, types: { '设备故障': 2, '温度过高': 2, '配件缺失': 2, '滤网堵塞': 2 }, device: { '心电监护仪A': 3, '注射泵B': 1, '呼吸机C': 1, '移动DR': 2, '血透机E': 1 } },
    { date: '6-08', 高: 4, 中: 4, 低: 1, total: 9, types: { '设备故障': 3, '温度过高': 2, '配件缺失': 2, '断电': 2 }, device: { '心电监护仪A': 2, '注射泵B': 2, '呼吸机C': 2, '移动DR': 2, '血透机E': 1 } },
    { date: '6-09', 高: 2, 中: 2, 低: 3, total: 7, types: { '设备故障': 2, '温度过高': 2, '配件缺失': 1, '滤网堵塞': 2 }, device: { '心电监护仪A': 2, '注射泵B': 1, '呼吸机C': 2, '移动DR': 1, '血透机E': 1 } },
    { date: '6-10', 高: 4, 中: 4, 低: 2, total: 10, types: { '设备故障': 4, '温度过高': 2, '配件缺失': 2, '断电': 2 }, device: { '心电监护仪A': 2, '注射泵B': 2, '呼吸机C': 2, '移动DR': 2, '血透机E': 2 } },
    { date: '6-11', 高: 2, 中: 3, 低: 1, total: 6, types: { '设备故障': 2, '温度过高': 1, '配件缺失': 2, '滤网堵塞': 1 }, device: { '心电监护仪A': 1, '注射泵B': 1, '呼吸机C': 1, '移动DR': 2, '血透机E': 1 } },
    { date: '6-12', 高: 1, 中: 1, 低: 1, total: 3, types: { '设备故障': 1, '温度过高': 1, '配件缺失': 1 }, device: { '心电监护仪A': 1, '注射泵B': 1, '呼吸机C': 1 } }
  ]
}
// 统计卡片区数据
const cardMap = { total: '总告警数', unhandled: '未处理', processing: '处理中', handled: '已处理' }
const cardData = computed(() => {
  // 这里简单用 trendDataRaw day 数据模拟
  const filtered = trendDataRaw[dateType.value]
  let total = 0, unhandled = 0, processing = 0, handled = 0
  for (const d of filtered) {
    total += d.total
    unhandled += Math.floor(d.total * 0.22)
    processing += Math.floor(d.total * 0.15)
    handled += d.total - Math.floor(d.total * 0.22) - Math.floor(d.total * 0.15)
  }
  return { total, unhandled, processing, handled }
})

// 1.告警趋势 折线图
const trendOption = computed(() => {
  const raw = trendDataRaw[dateType.value]
  const x = raw.map(d => d.date)
  let y = raw.map(d => d.total)
  // 筛选级别
  if (level.value) y = raw.map(d => d[level.value])
  // 筛选类型
  if (type.value) y = raw.map(d => d.types[type.value] || 0)
  return {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: x },
    yAxis: { type: 'value' },
    series: [
      { name: '告警数', type: 'line', smooth: true, data: y, areaStyle: {} }
    ]
  }
})

// 2.级别分布 饼图
const levelPieOption = computed(() => {
  const raw = trendDataRaw[dateType.value]
  let levelData = { 高: 0, 中: 0, 低: 0 }
  for (const d of raw) {
    levelData.高 += d.高
    levelData.中 += d.中
    levelData.低 += d.低
  }
  // 如选定类型，只统计该类型
  if (type.value) {
    levelData = { 高: 0, 中: 0, 低: 0 }
    for (const d of raw) {
      // 这里模拟，高级别类型多一些
      if (d.types[type.value]) {
        if (type.value === '设备故障' || type.value === '断电') levelData.高 += d.types[type.value]
        else if (type.value === '温度过高' || type.value === '配件缺失') levelData.中 += d.types[type.value]
        else levelData.低 += d.types[type.value]
      }
    }
  }
  const data = [
    { value: levelData.高, name: '高' },
    { value: levelData.中, name: '中' },
    { value: levelData.低, name: '低' }
  ]
  return {
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    legend: { top: '5%', left: 'center' },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        label: {
          show: true,
          formatter: '{b}\n{c} ({d}%)',
          fontSize: 13
        },
        data
      }
    ]
  }
})

// 3.类型TOP5
const typeTopOption = computed(() => {
  const raw = trendDataRaw[dateType.value]
  const sum = {}
  for (const d of raw) {
    for (const k in d.types) {
      sum[k] = (sum[k] || 0) + d.types[k]
    }
  }
  let arr = Object.entries(sum).map(([k, v]) => ({ name: k, value: v }))
  // 按级别筛选
  if (level.value) {
    // 这里只演示：如级别为高，只选高风险类型
    arr = arr.filter(a => level.value === '高' ? ['设备故障','断电'].includes(a.name) : true)
  }
  arr.sort((a, b) => b.value - a.value)
  arr = arr.slice(0, 5)
  return {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'value' },
    yAxis: {
      type: 'category',
      data: arr.map(a => a.name),
      inverse: true
    },
    series: [
      {
        name: '告警数',
        type: 'bar',
        data: arr.map(a => a.value),
        label: { show: true, position: 'right' }
      }
    ],
    grid: { left: 100, right: 20, bottom: 20, top: 24 }
  }
})

// 4.设备TOP5
const deviceTopOption = computed(() => {
  const raw = trendDataRaw[dateType.value]
  const sum = {}
  for (const d of raw) {
    for (const k in d.device) {
      sum[k] = (sum[k] || 0) + d.device[k]
    }
  }
  let arr = Object.entries(sum).map(([k, v]) => ({ name: k, value: v }))
  arr.sort((a, b) => b.value - a.value)
  arr = arr.slice(0, 5)
  return {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'value' },
    yAxis: {
      type: 'category',
      data: arr.map(a => a.name),
      inverse: true
    },
    series: [
      {
        name: '告警数',
        type: 'bar',
        data: arr.map(a => a.value),
        label: { show: true, position: 'right' }
      }
    ],
    grid: { left: 100, right: 20, bottom: 20, top: 24 }
  }
})

// Excel导出
function exportExcel() {
  const data = [
    ['日期', '总告警', '高', '中', '低'],
    ...trendDataRaw[dateType.value].map(d => [d.date, d.total, d.高, d.中, d.低])
  ]
  const ws = XLSX.utils.aoa_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '告警趋势')
  XLSX.writeFile(wb, '告警统计分析.xlsx')
  ElMessage.success('已导出Excel')
}

// 下载全部图表
const trendRef = ref(), levelRef = ref(), typeTopRef = ref(), deviceTopRef = ref()
async function downloadAllImages() {
  await nextTick()
  const refs = [trendRef, levelRef, typeTopRef, deviceTopRef]
  const names = ['告警趋势','级别分布','类型TOP5','设备TOP5']
  for(let i=0;i<refs.length;i++){
    const chartInstance = refs[i].value?.chart
    if (!chartInstance) continue
    const imgData = chartInstance.getDataURL({ type: 'png', pixelRatio: 2, backgroundColor: '#fff' })
    const a = document.createElement('a')
    a.href = imgData
    a.download = `${names[i]}.png`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }
  ElMessage.success('所有图表已下载')
}
</script>

<style scoped>
.stat-page {
 max-height: calc(100vh - 40px); /* 视口高度减去头部或导航 */
  overflow-y: auto;
  padding-bottom: 24px;
}
.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
}
.title {
  font-size: 20px;
  font-weight: bold;
  margin-right: 20px;
}
.stat-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 6px;
}
.stat-cards {
  margin-bottom: 8px;
}
.card-num {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  text-align: center;
  line-height: 1.1;
  min-height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.card-num.total { color: #5470C6; }
.card-num.unhandled { color: #EE6666; }
.card-num.processing { color: #FAC858; }
.card-num.handled { color: #91CC75; }
</style>
